import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { useTheme } from "@/hooks/useTheme";
import { toast } from "sonner";
import { MilkdownPreview, fontOptions } from "@/components/MilkdownPreview";
import { publicApi } from "@/services/api";
import type { ApiResponse } from "@/services/api";

interface DocData {
  docId: string;
  docTitle: string;
  docContent: string;
  createUser?: string;
  createTime?: string;
  updateUser?: string;
  updateTime?: string;
}

export default function DocShare() {
  const { id: docId } = useParams<{ id: string }>();
  const { theme, toggleTheme, isDark } = useTheme();
  const [docData, setDocData] = useState<DocData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedFont, setSelectedFont] = useState('inter');

  // 加载文档数据
  useEffect(() => {
    if (!docId) {
      setError('缺少文档ID');
      setIsLoading(false);
      return;
    }

    const fetchDocData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        
        const res: ApiResponse = await publicApi({
          url: '/doc/getDocByDocId',
          method: 'post',
          data: {
            docId
          }
        });

        if (res && res.success) {
          setDocData({
            docId: res.data?.docId || docId,
            docTitle: res.data?.docTitle || '未命名文档',
            docContent: res.data?.docContent || '',
            createUser: res.data?.createUser,
            createTime: res.data?.createTime,
            updateUser: res.data?.updateUser,
            updateTime: res.data?.updateTime
          });
        } else {
          setError(res?.message || '加载文档失败');
        }
      } catch (error: any) {
        console.error('加载文档失败:', error);
        setError(error.message || '加载文档失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchDocData();
  }, [docId]);

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60 dark:bg-black flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">加载中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60 dark:bg-black flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-500 text-6xl mb-4">⚠️</div>
          <h2 className="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">加载失败</h2>
          <p className="text-gray-600 dark:text-gray-400">{error}</p>
        </div>
      </div>
    );
  }

  if (!docData) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60 dark:bg-black flex items-center justify-center">
        <div className="text-center">
          <div className="text-gray-400 text-6xl mb-4">📄</div>
          <h2 className="text-xl font-semibold text-gray-600 dark:text-gray-400 mb-2">
            文档不存在
          </h2>
          <p className="text-gray-500 dark:text-gray-500">
            该文档可能已被删除或不存在
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-100/70 via-blue-100/50 to-purple-100/60 dark:bg-black">
      {/* 顶部导航栏 */}
      <div className="bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-b border-gray-200 dark:border-gray-700">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center">
              <h1 className="text-xl font-semibold text-gray-900 dark:text-white">
                文档分享
              </h1>
            </div>
            <div className="flex items-center space-x-4">
              <button
                onClick={toggleTheme}
                className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
              >
                {isDark ? (
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
                  </svg>
                ) : (
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
                  </svg>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm rounded-lg shadow-lg p-8">
          {/* 文档标题和元信息 */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-4">
              <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
                {docData.docTitle}
              </h1>
              <div className="flex items-center space-x-4">
                <select
                  value={selectedFont}
                  onChange={(e) => setSelectedFont(e.target.value)}
                  className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-sm"
                >
                  {fontOptions.map((font) => (
                    <option key={font.value} value={font.value}>
                      {font.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            
            {/* 文档元信息 */}
            {(docData.createUser || docData.createTime || docData.updateUser || docData.updateTime) && (
              <div className="flex flex-wrap gap-4 text-sm text-gray-600 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700 pt-4">
                {docData.createUser && (
                  <div className="flex items-center">
                    <span className="mr-1">创建者:</span>
                    <span className="font-medium">{docData.createUser}</span>
                  </div>
                )}
                {docData.createTime && (
                  <div className="flex items-center">
                    <span className="mr-1">创建时间:</span>
                    <span className="font-medium">{new Date(docData.createTime).toLocaleString()}</span>
                  </div>
                )}
                {docData.updateUser && (
                  <div className="flex items-center">
                    <span className="mr-1">更新者:</span>
                    <span className="font-medium">{docData.updateUser}</span>
                  </div>
                )}
                {docData.updateTime && (
                  <div className="flex items-center">
                    <span className="mr-1">更新时间:</span>
                    <span className="font-medium">{new Date(docData.updateTime).toLocaleString()}</span>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* 文档内容 */}
          <div className="prose prose-lg max-w-none dark:prose-invert">
            <MilkdownPreview
              content={docData.docContent}
              selectedFont={selectedFont}
            />
          </div>
        </div>
      </div>
    </div>
  );
} 